import { useEffect, useState, useImperativeHandle, forwardRef } from 'react';
import styles from './index.less';
import { Modal, Table } from 'antd';
import { connect } from 'umi';
import { tableLocale } from '@/tool/components/PageEmpty';
import { TRMessage } from '#/components';
import { HttpCode } from '#/utils/contacts.js';
import { programOverviewModal } from '@/assets';
import { fetchUnitSubmitInfos } from '@/pages/Tianji/TenDaysCentralizedBidding/services';
import moment from 'moment';

const { Column } = Table;

function ProgramOverviewModal({ tradeSeqId, menuCode, market = {}, formData }, ref) {
  useImperativeHandle(ref, () => ({
    initHandle,
  }));

  const [showModal, setShowModal] = useState(false),
    [programUnits, setProgramUnits] = useState([]),
    [formatProgramUnits, setFormatProgramUnits] = useState([]),
    [columnList, setColumnList] = useState([]),
    [loading, setLoading] = useState(false);
  const is_SD = market.value === 'PHBSD';
  const initHandle = () => {
    setShowModal(true);
    fetchUnitSubmitInfosFunc();
  };

  async function fetchUnitSubmitInfosFunc() {
    setLoading(true);
    const _tradeSeqId =
      market?.value +
      '/' +
      (tradeSeqId.includes('PHBSX') ? tradeSeqId : market?.value + tradeSeqId);
    const res = await fetchUnitSubmitInfos(_tradeSeqId, menuCode);
    setLoading(false);
    if (res?.statusCode === HttpCode.SUCCESS) {
      setProgramUnits(res?.data?.programUnits);
    } else {
      TRMessage.error(res?.message || '获取方案总览信息失败');
    }
  }

  useEffect(() => {
    setFormatProgramUnits([]);
    if (!programUnits.length) return;
    let columnList = [];
    let formatProgramUnits = [];
    // 格式化columnList
    programUnits.forEach((item) => {
      let obj = {
        title: item.unitTitle,
        key: item.unitId + 'TotalPower',
        strategy: item.unitId + 'Strategy',
      };
      columnList.push(obj);
    });
    if (is_SD) {
      programUnits.forEach((item) => {
        if (item?.unitDateMapping) {
          Object.entries(item.unitDateMapping).forEach((t, i) => {
            if (formatProgramUnits[i]) {
              formatProgramUnits[i][item.unitId + 'TotalPower'] = t[1]?.totalPower || 0;
              formatProgramUnits[i][item.unitId + 'Strategy'] = t[1]?.tradeStrategy || 0;
              return;
            }
            const obj = {
              hourOrder: t[0],
              [item.unitId + 'TotalPower']: t[1]?.totalPower || 0,
              [item.unitId + 'Strategy']: t[1]?.tradeStrategy || 0,
            };
            formatProgramUnits.push(obj);
          });
        }
      });
    } else {
      // 格式化formatProgramUnits
      for (var i = 1; i <= 24; i++) {
        let obj = {
          hourOrder: i,
        };
        formatProgramUnits.push(obj);
      }
      programUnits.forEach((item) => {
        for (var i = 1; i <= 24; i++) {
          if (item.unitHourOrderMapping) {
            formatProgramUnits[i - 1][item.unitId + 'TotalPower'] =
              item.unitHourOrderMapping?.[i]?.totalPower || 0;
            formatProgramUnits[i - 1][item.unitId + 'Strategy'] =
              item.unitHourOrderMapping?.[i]?.tradeStrategy || 0;
          } else {
            formatProgramUnits[i - 1][item.unitId + 'TotalPower'] = '-';
          }
        }
      });
    }
    // 获取交易单元所属方案
    let programObj = {
      hourOrder: '所属方案',
    };
    programUnits.forEach((item) => {
      programObj[item.unitId + 'TotalPower'] = item.programTitle || '-';
    });
    formatProgramUnits.unshift(programObj);
    setColumnList(columnList);
    setFormatProgramUnits(formatProgramUnits);
  }, [programUnits]);

  return (
    <Modal
      className={styles.programOverviewModal}
      centered={true}
      title={
        <div className={styles.modalTitle}>
          <img src={programOverviewModal} />
          <span className={styles.text}>待申报方案总览</span>
          <div className={styles.unit}>
            <span className={styles.label}>单位：</span>MWh
          </div>
        </div>
      }
      visible={showModal}
      footer={null}
      onCancel={() => {
        setShowModal(false);
      }}
    >
      <Table
        loading={loading}
        className={styles.table}
        dataSource={formatProgramUnits}
        rowKey="hourOrder"
        bordered={true}
        locale={tableLocale}
        pagination={false}
        scroll={{ x: true }}
        rowClassName={(record) => {
          if (record.hourOrder === '所属方案' || record.hourOrder === '申报结果') {
            return 'extraInfo';
          }
        }}
      >
        <Column
          title={is_SD ? '日期' : '时点'}
          align="center"
          dataIndex="hourOrder"
          key="hourOrder"
          width={is_SD ? 100 : 76}
          fixed="left"
        />
        {columnList.map((item) => (
          <Column
            title={
              <>
                <div>{item.title}</div>
                <div>{is_SD ? '申报电量' : '(段一量+段二量)'}</div>
              </>
            }
            className={styles.stationsColumn}
            align="center"
            dataIndex={item.key}
            key={item.key}
            render={(text, record) => {
              switch (record[item.strategy]) {
                case 0:
                  return <span className={styles.red}>{text ?? '-'}</span>;
                case 1:
                  return <span className={styles.green}>{text ?? '-'}</span>;
                case 2:
                  return <span className={styles.yellow}>不交易</span>;
                case 3:
                  return <span className={styles.gray}>无策略</span>;
                default:
                  return <>{text ?? '-'}</>;
              }
            }}
          />
        ))}
      </Table>
    </Modal>
  );
}

export default connect(
  ({ global, tenDaysCentralizedBidding }) => ({
    menuCode: global.configure.menuCode,
    tradeSeqId: tenDaysCentralizedBidding.tradeSeqId,
  }),
  null,
  null,
  { forwardRef: true },
)(forwardRef(ProgramOverviewModal));
